package com.regex.web.controller;


import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.regex.web.cache.DictCacheService;
import com.regex.web.common.excel.ExportExcel;
import com.regex.web.entity.sys.DictDTO;
import com.regex.web.service.sys.IDictService;
import com.regex.web.utils.AjaxUtil;
import com.regex.web.utils.Contant;
import com.regex.web.utils.QueryResult;
import com.regex.web.vo.LayTableDataVO;
import com.regex.web.vo.ResultVO;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mhy
 * @since 2020-05-06
 */
@Controller
@RequestMapping("sys/dict")
public class DictController {

	private final static Logger logger = LoggerFactory.getLogger(DictController.class);
	
	@Autowired
	private IDictService IDictService;
	
	@Autowired
    private DictCacheService dictCacheService;
	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param dictDTO
	 * @return
	 */
	@RequestMapping("show")
	public String show() {
		return "sys/dict/show";
	}
	
	
	@RequestMapping("getPageData")
	public void getPageData(HttpServletResponse response,
			DictDTO DictDTO, String limit, String page) {
		LayTableDataVO<DictDTO> result = new LayTableDataVO<DictDTO>();
		try {
			
			QueryWrapper<DictDTO> param = new QueryWrapper<DictDTO>();
			if(StringUtils.isNotEmpty(DictDTO.getType())) {
				param.eq("type", DictDTO.getType());
			}
			if(StringUtils.isNotEmpty(DictDTO.getDescription())) {
				param.eq("description", DictDTO.getDescription());
			}
			param.orderByDesc("create_time");
			Page<DictDTO> pageParam = new Page<DictDTO>();
			if (StringUtils.isEmpty(limit)) {
				limit = Contant.NONMAL_PAGE_SIZE_TEN + "";
			}
			if (StringUtils.isEmpty(page)) {
				page = Contant.NONMAL_PAGE_START + "";
			}
			pageParam.setSize(Integer.parseInt(limit));
			pageParam.setCurrent(Integer.parseInt(page));
			
	        QueryResult<DictDTO> pageResult = IDictService.page(pageParam, param);
			
			result.setData(pageResult.getDatas());
			result.setCode(0);
			result.setCount(pageResult.getTotalDataCount());
		} catch (Exception e) {
			result.setCode(500);
			AjaxUtil.ajaxJsonSucMessage(response, result);
			e.printStackTrace();
		}
		AjaxUtil.ajaxJsonSucMessage(response, result);
	}
	
	/**
	 * 编辑/新增
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("input")
    public String toSave(String id, Model model) {
    	try {
	        if(StringUtils.isNotEmpty(id)) {
	        	DictDTO dictDTO = IDictService.getById(id);
	            model.addAttribute("dictDTO", dictDTO);
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("toSave page is Exception!");
		}
        return "sys/dict/input";
    }
    
    /**
	 * 保存
	 * @param dictDTO
	 * @param response
	 */
    @PostMapping("save")
	@ResponseBody
	public ResultVO<String> save(@Valid  @RequestBody DictDTO dictDTO, HttpServletResponse response) {
		ResultVO<String> result = new ResultVO<String>();
		boolean flag = false;
		if(dictDTO.getId() != null && dictDTO.getId().longValue() > 0) {
			dictDTO.setUpdateTime(new Date());
			flag = IDictService.updateById(dictDTO);
			if(flag) {
            	return ResultVO.success();
            }
		} else {
			dictDTO.setIsDel(Contant.is_del_undelete);
			dictDTO.setUpdateTime(new Date());
			dictDTO.setCreateTime(new Date());
			flag = IDictService.save(dictDTO);
			if(flag) {
            	return ResultVO.success();
            }
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("detial")
    public String detial(String id, Model model) {
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	DictDTO dictDTO = IDictService.getById(id);
	            model.addAttribute("dictDTO", dictDTO);
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("detial page is Exception!");
		}
        return "sys/dict/detial";
    }
	
	/**
	 * 删除
	 * @param id
	 * @param response
	 */
	@RequestMapping("del")
    public void del(String id, HttpServletResponse response) {
        int n = 0;
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	boolean flag = IDictService.removeById(id);
	        	if(flag) {
	        		n = 1;
	        	}
	        } else {
	        	n = 2;
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("del page is Exception!");
		}
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    /**
	 * 导出
	 * @param response
	 * @param dictDTO
	 * @return
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(HttpServletResponse response, @ModelAttribute("dictDTO") DictDTO dictDTO) {
        try {
            QueryWrapper<DictDTO> param = new QueryWrapper<DictDTO>(dictDTO);
        	
        	String fileName = "数据"+(new Date()).getTime()+".xlsx";
            
            List<DictDTO> datas = IDictService.list(param);
            new ExportExcel("数据", DictDTO.class).setDataList(datas).write(response, fileName).dispose();
            return null; 
        } catch (Exception e) {
        	logger.error("exportFile page is Exception!");
            e.printStackTrace();
        }
        return "redirect:show.htm";
    }
    
    @RequestMapping("getDictData")
    public void getDictData(HttpServletResponse response) {
    	LinkedHashMap<String, Object> dictMap = dictCacheService.getDictCache();
        AjaxUtil.ajaxJsonSucMessage(response, dictMap);
    }
	
}
